package com.cy.springcloudalibaba.handlers;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.cy.springcloudalibaba.dtos.RestDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 自定义sentinel异常处理器
 * @ClassName: SentinelExceptionHandler
 * @Author: chenyu
 * @Date: 2025/1/17 14:20
 */
@Slf4j
@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        log.info("UrlBlockHandler......");
        RestDto restDto = null;
        if (e instanceof FlowException) {
            restDto = RestDto.builder().statusCode(100).statusMessage("接口限流了").build();
        }
        else if (e instanceof DegradeException) {
            restDto = RestDto.builder().statusCode(101).statusMessage("服务降级了").build();
        }
        else if (e instanceof ParamFlowException) {
            restDto = RestDto.builder().statusCode(102).statusMessage("热点参数限流了").build();
        }
        else if (e instanceof SystemBlockException) {
            restDto = RestDto.builder().statusCode(103).statusMessage("触发系统保护规则").build();
        }
        else if (e instanceof AuthorityException) {
            restDto = RestDto.builder().statusCode(104).statusMessage("授权规则不通过").build();
        }

        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //springmvc的一个json转换类（jackson）
        new ObjectMapper().writeValue(httpServletResponse.getWriter(), restDto);
    }
}
